//
//  HBHistoryController.m
//  HeartBeat
//
//  Created by karong on 2023/8/28.
//

#import "HBHistoryController.h"
#import "HBHistoryCell.h"
#import "HBhistoryRequest.h"
#import "HBHistoryModel.h"
@interface HBHistoryController () <HBHistoryCellDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *editBarBottom;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, strong) NSMutableArray * todayArray;
@property (nonatomic, strong) NSMutableArray * yestodayArray;
@property (nonatomic, strong) NSMutableArray * beforeArray;
@property (nonatomic, assign) BOOL needReload;
@end

@implementation HBHistoryController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.needReload) {
        self.needReload = NO;
        [self benginRefresh];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addObserver];
    HBhistoryRequest * request = [HBhistoryRequest new];
    self.request = request;
    [self setEmptyStateTitle:WSLocalized(@"歷史空空的") state:(HBListViewEmptyStateEmpty)];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needReloadData) name:HBRefreshFollowNotification object:nil];
    
}

- (void)needReloadData {
    if ([[UIViewController currentViewController] isKindOfClass:NSClassFromString(@"HBFollowController")]) {
        [self benginRefresh];
    }
    else {
        self.needReload = YES;
    }
}

- (void)loadSuccessWithArray:(NSArray *)array isRefresh:(BOOL)isRefresh {
    NSMutableArray * tArray = [[NSMutableArray alloc]init];
    NSMutableArray * yArray = [[NSMutableArray alloc]init];
    NSMutableArray * bArray = [[NSMutableArray alloc]init];
    for (HBHistoryModel * history in array) {
        if (history.period == 1) {
            [tArray addObject:history];
        }
        if (history.period == 2) {
            [yArray addObject:history];
        }
        if (history.period == 3) {
            [bArray addObject:history];
        }
    }
    if (isRefresh) {
        [self.todayArray removeAllObjects];
        self.todayArray = [NSMutableArray new];
        [self.yestodayArray removeAllObjects];
        self.yestodayArray = [NSMutableArray new];
        [self.beforeArray removeAllObjects];
        self.beforeArray = [NSMutableArray new];
    }
    [self.todayArray addObjectsFromArray:tArray];
    [self.yestodayArray addObjectsFromArray:yArray];
    [self.beforeArray addObjectsFromArray:bArray];
    [super loadSuccessWithArray:array isRefresh:isRefresh];
}

- (BOOL)disableAutoBeginRefresh {
    return YES;
}

- (void)addFollowRequest:(NSArray *)addArray success:(空回调)success {
    [HBToast loading];
    [HBRequest addBookshelfWithAddArray:addArray success:^{
        [HBToast dismiss];
        success();
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)delHistoryRequest:(NSArray*)array {
    [HBToast loading];
    [HBRequest delHistoryWithDelArray:array success:^{
        [HBToast dismiss];
        [self.dataArray removeObjectsInArray:array];
        [self endEdit];
        [self benginRefresh];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)beginEdit {
    self.isEdit = YES;
}

- (void)endEdit {
    self.isEdit = NO;
}

- (NSInteger)dataArrayCount {
    return self.dataArray.count;
}

- (IBAction)addFollowAction:(UIButton *)sender {
    NSMutableArray * addArray = [NSMutableArray new];
    for (HBHistoryModel * history in self.dataArray) {
        if (history.isSelected) {
            [addArray addObject:history];
        }
    }
    if (addArray.count > 0) {
        WeakSelf
        [self addFollowRequest:addArray success:^{
            for (HBHistoryModel * history in addArray) {
                history.is_bookshelf = YES;
            }
            [weakSelf endEdit];
            [weakSelf.listView reloadData];
        }];
    }
    else {
        [self endEdit];
    }
    
}

- (IBAction)deleteAction:(id)sender {
    NSMutableArray * delArray = [NSMutableArray new];
    for (HBHistoryModel * history in self.dataArray) {
        if (history.isSelected) {
            [delArray addObject:history];
        }
    }
    if (delArray.count > 0) {
        [self delHistoryRequest:delArray];
    }
    else {
        [self endEdit];
    }
}



- (void)initArraySelectStatus {
    for (HBHistoryModel * history in self.dataArray) {
        history.isSelected = NO;
    }
}

- (void)layoutDeleteBtnStatus {
    BOOL rec = NO;
    for (HBHistoryModel * history in self.dataArray) {
        if (history.isSelected) {
            rec = YES;
            break;
        }
    }
    
    self.deleteBtn.backgroundColor = rec?UIColor.font_yellow_FFCC00:[UIColor colorFromHexRGB:@"e5e5e5"];
    [self.deleteBtn setTitleColor:rec?UIColor.font_black_1A1A1A:UIColor.font_white_ffffff forState:(UIControlStateNormal)];
}
#pragma mark CollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = 0;
    if (section == 0) {
        count = self.todayArray.count;
    }
    else if (section == 1) {
        count = self.yestodayArray.count;
    }
    else if (section == 2) {
        count = self.beforeArray.count;
    }
    return count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HBHistoryCell * historyCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBHistoryCell" forIndexPath:indexPath];
    historyCell.delegate = self;
    if (indexPath.section == 0) {
        [historyCell setDataWithObject:self.todayArray[indexPath.row] edit:self.isEdit];
    }
    else if (indexPath.section == 1) {
        [historyCell setDataWithObject:self.yestodayArray[indexPath.row] edit:self.isEdit];
    }
    else if (indexPath.section == 2) {
        [historyCell setDataWithObject:self.beforeArray[indexPath.row] edit:self.isEdit];
    }
    return historyCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    HBHistoryModel * history;
    if (indexPath.section == 0) {
        history = self.todayArray[indexPath.row];
    }
    else if (indexPath.section == 1) {
        history = self.yestodayArray[indexPath.row];
    }
    else if (indexPath.section == 2) {
        history = self.beforeArray[indexPath.row];
    }
    if (self.isEdit) {
        history.isSelected = !history.isSelected;
        [self layoutDeleteBtnStatus];
        [self.listView reloadItemsAtIndexPaths:@[indexPath]];
    }
    else {
        [ViewManager pushReadVCWithNovel_id:history.book_id chapter_id:history.chapter_id inController:self];
        [HBEvenManager event:@"book_tracking" evenLogType:(HBEvenLogType_Click)
                  attributes:@{@"page_view":@"2"}];
    }
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView * historyHeadView;
        if (!historyHeadView) {
            historyHeadView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HBHistoryHeadView" forIndexPath:indexPath];
            UILabel * label = [historyHeadView viewWithTag:101];
            label.text = @[WSLocalized(@"今天"),WSLocalized(@"昨天"),WSLocalized(@"更早")][indexPath.section];
        }
        return historyHeadView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGSize size = CGSizeZero;
    size.width = HBScreenWidth;
    if ((self.todayArray.count > 0 && section == 0) || (self.yestodayArray.count > 0 && section == 1) || (self.beforeArray.count > 0 && section == 2)) {
        size.height = 47;
    }
    return size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    CGFloat width = 70;
    size.width = HBScreenWidth;
    size.height = width * 4 / 3.0f;
    return size;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 12;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(nonnull UICollectionViewCell *)cell forItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    [HBEvenManager event:@"shelf_add" evenLogType:(HBEvenLogType_Pop)
              attributes:@{@"type_selection":@"2"}];
}

- (void)setIsEdit:(BOOL)isEdit {
    _isEdit = isEdit;
    self.editBarBottom.constant = isEdit?0:-80;
    [self.view uploadLayout];
    if (isEdit) {
        [self initArraySelectStatus];
        [self layoutDeleteBtnStatus];
    }
    else {
        if ([self.delegate respondsToSelector:@selector(historyControllerExitEdit)]) {
            [self.delegate historyControllerExitEdit];
        }
    }
    [self.listView reloadData];
}

- (void)historyCell:(UICollectionViewCell *)cell addAction:(HBNovelModel *)object {
    WeakSelf
    [self addFollowRequest:@[object] success:^{
        object.is_bookshelf = YES;
        NSIndexPath * indexPath = [weakSelf.listView indexPathForCell:cell];
        [weakSelf.listView reloadItemsAtIndexPaths:@[indexPath]];
    }];
    [HBEvenManager event:@"shelf_add" evenLogType:(HBEvenLogType_Click)
              attributes:@{@"type_selection":@"3"}];
}
@end
